#!/usr/bin/ruby

input = ""
ARGV.each do |b|
    input = b
end

if input == ""
  puts "
  This tool parses RestKit logging output and turns it into a curl request so you can see what is going on easier. Simply copy and paste the 'Headers' and 'Sending' lines out of the XCode Console and pass them in to this tool to see the curl request & response.
  This is an easy way to see the output from an RKRequest.
  
  USAGE:\n./rkcurl \"2011-01-20 11:40:07.122 DiscussionBoard[25362:40b] Headers: {
      Accept = \"application/json\";
      \"X-User-Access-Token\" = csitBupAGxaNVVX6XSo;
  }
  2011-01-20 11:40:07.123 DiscussionBoard[25362:40b] Sending GET request to URL http://discussionboard.heroku.com/topics/4/posts. HTTP Body: 
  \"
  "
  exit 0
end

headersString = input.match(/.*Headers: \{(.*)\}/m)[1]
headers = []

headersString.each_line do |line|
  next if line.strip.size == 0
	headers << line.strip.gsub(";", "").gsub(" = ", ": ")
end

method = input.match(/Sending (.*) request to/m)[1]
url = input.match(/URL (.*)\. HTTP Body/m)[1]

data = nil
dataMatch = input.match(/HTTP Body: (.*)\n/m)
data = dataMatch[1] if dataMatch

command = "curl -i -X #{method} "
command << "-d \"#{data.gsub('"', '\"')}\" " if data
for header in headers
  command << "-H \"#{header.gsub('"', '\"')}\" "
end
command << url

puts command

output = `#{command}`

puts output